<!DOCTYPE html>
<html>
<head>
    <title>隐私API配置管理</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .nav-link { cursor: pointer; }
        .method-item { margin-bottom: 10px; }
        .action-buttons { white-space: nowrap; }
    </style>
</head>
<body>
    <div class="container-fluid mt-3">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>隐私API配置管理</h2>
                    <div>
                        <a href="/" class="btn btn-secondary me-2">
                            <i class="bi bi-arrow-left"></i> 返回主页
                        </a>
                        <button class="btn btn-success me-2" onclick="addCategory()">
                            <i class="bi bi-plus-circle"></i> 添加分类
                        </button>
                        <button class="btn btn-primary me-2" onclick="saveConfig()">
                            <i class="bi bi-save"></i> 保存配置
                        </button>
                        <button class="btn btn-info" onclick="exportToExcel()">
                            <i class="bi bi-file-earmark-excel"></i> 导出Excel
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body" id="categoriesContainer">
                        <!-- 分类内容将通过JavaScript动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑分类的模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalTitle">添加分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="categoryForm">
                        <div class="mb-3">
                            <label class="form-label">分类ID</label>
                            <input type="text" class="form-control" id="categoryId" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <input type="text" class="form-control" id="categoryDescription" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">标签</label>
                            <input type="text" class="form-control" id="categoryTag" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveCategory()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑方法的模态框 -->
    <div class="modal fade" id="methodModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="methodModalTitle">添加方法</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="methodForm">
                        <input type="hidden" id="categoryIdForMethod">
                        <div class="mb-3">
                            <label class="form-label">方法名(完整类名.方法名)</label>
                            <input type="text" class="form-control" id="methodName" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveMethod()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.17.0/dist/xlsx.full.min.js"></script>
    <script>
        let currentConfig = null;
        const categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
        const methodModal = new bootstrap.Modal(document.getElementById('methodModal'));

        // 页面加载时获取配置
        window.onload = function() {
            fetchConfig();
        };

        // 获取配置
        function fetchConfig() {
            fetch('/api/config')
                .then(response => response.json())
                .then(data => {
                    currentConfig = data;
                    renderConfig();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载配置失败');
                });
        }

        // 渲染配置
        function renderConfig() {
            const container = document.getElementById('categoriesContainer');
            container.innerHTML = '';

            for (const [categoryId, category] of Object.entries(currentConfig.apis)) {
                const categoryHtml = `
                    <div class="card mb-3" id="category-${categoryId}">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">${category.description} (${category.tag})</h5>
                                <div>
                                    <button class="btn btn-sm btn-primary me-2" onclick="addMethod('${categoryId}')">
                                        <i class="bi bi-plus"></i> 添加方法
                                    </button>
                                    <button class="btn btn-sm btn-warning me-2" onclick="editCategory('${categoryId}')">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteCategory('${categoryId}')">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="method-list">
                                ${category.methods.map(method => `
                                    <div class="method-item d-flex justify-content-between align-items-center">
                                        <code>${method}</code>
                                        <button class="btn btn-sm btn-danger" onclick="deleteMethod('${categoryId}', '${method}')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                `;
                container.insertAdjacentHTML('beforeend', categoryHtml);
            }
        }

        // 添加分类
        function addCategory() {
            document.getElementById('categoryModalTitle').textContent = '添加分类';
            document.getElementById('categoryForm').reset();
            categoryModal.show();
        }

        // 编辑分类
        function editCategory(categoryId) {
            const category = currentConfig.apis[categoryId];
            document.getElementById('categoryModalTitle').textContent = '编辑分类';
            document.getElementById('categoryId').value = categoryId;
            document.getElementById('categoryDescription').value = category.description;
            document.getElementById('categoryTag').value = category.tag;
            categoryModal.show();
        }

        // 保存分类
        function saveCategory() {
            const categoryId = document.getElementById('categoryId').value;
            const description = document.getElementById('categoryDescription').value;
            const tag = document.getElementById('categoryTag').value;

            if (!currentConfig.apis[categoryId]) {
                currentConfig.apis[categoryId] = {
                    description: description,
                    tag: tag,
                    methods: []
                };
            } else {
                currentConfig.apis[categoryId].description = description;
                currentConfig.apis[categoryId].tag = tag;
            }

            renderConfig();
            categoryModal.hide();
        }

        // 删除分类
        function deleteCategory(categoryId) {
            if (confirm('确定要删除此分类吗？')) {
                delete currentConfig.apis[categoryId];
                renderConfig();
            }
        }

        // 添加方法
        function addMethod(categoryId) {
            document.getElementById('methodModalTitle').textContent = '添加方法';
            document.getElementById('methodForm').reset();
            document.getElementById('categoryIdForMethod').value = categoryId;
            methodModal.show();
        }

        // 保存方法
        function saveMethod() {
            const categoryId = document.getElementById('categoryIdForMethod').value;
            const methodName = document.getElementById('methodName').value;

            if (!currentConfig.apis[categoryId].methods.includes(methodName)) {
                currentConfig.apis[categoryId].methods.push(methodName);
                renderConfig();
            }

            methodModal.hide();
        }

        // 删除方法
        function deleteMethod(categoryId, method) {
            if (confirm('确定要删除此方法吗？')) {
                currentConfig.apis[categoryId].methods = currentConfig.apis[categoryId].methods.filter(m => m !== method);
                renderConfig();
            }
        }

        // 保存配置
        function saveConfig() {
            currentConfig.lastUpdated = new Date().toISOString().split('T')[0];
            fetch('/api/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(currentConfig)
            })
            .then(response => response.json())
            .then(data => {
                alert('配置保存成功');
            })
            .catch((error) => {
                console.error('Error:', error);
                alert('保存失败');
            });
        }

        // 导出Excel
        function exportToExcel() {
            const workbook = XLSX.utils.book_new();
            const data = [];
            
            // 添加表头
            data.push(['分类', '标签', '描述', '方法']);
            
            // 添加数据
            for (const [categoryId, category] of Object.entries(currentConfig.apis)) {
                category.methods.forEach(method => {
                    data.push([
                        categoryId,
                        category.tag,
                        category.description,
                        method
                    ]);
                });
            }
            
            const worksheet = XLSX.utils.aoa_to_sheet(data);
            XLSX.utils.book_append_sheet(workbook, worksheet, "API配置");
            
            // 生成Excel文件并下载
            XLSX.writeFile(workbook, `privacy_api_config_${new Date().toISOString().split('T')[0]}.xlsx`);
        }
    </script>
</body>
</html>
